<template>
  <div>
    <el-table :data="tableData" border style="width: 100%; border-collapse: collapse">
      <el-table-column prop="id" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="图书名" width="150"></el-table-column>
      <el-table-column prop="author" label="作者" width="120"></el-table-column>
      <el-table-column prop="publish" label="出版社" width="180"></el-table-column>
      <el-table-column prop="pages" label="页数" width="80" align="center"></el-table-column>
      <el-table-column prop="price" label="价格" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.price ? scope.row.price.toFixed(2) : 'N/A' }}
        </template>
      </el-table-column>
      <el-table-column prop="bookcaseid" label="书架ID" width="80" align="center"></el-table-column>
      <el-table-column prop="abled" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.abled === 1 ? 'success' : 'danger'">
            {{ scope.row.abled === 1 ? '可用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="335" align="center">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center; align-items: center; gap: 10px">
            <el-tooltip content="编辑" placement="top">
              <el-button @click="edit(scope.row)" type="primary" icon="el-icon-edit" size="small" circle>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button @click="deleteBook(scope.row)" type="danger" icon="el-icon-delete" size="small" circle>
              </el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next, sizes, jumper, ->, total" :page-sizes="[5, 10, 20]" :page-size="pageSize" :total="total" :current-page="currentPage" @current-change="page" @size-change="handleSizeChange" style="margin-top: 20px;">
      <template #default="{pager}">
        <span class="el-pagination__total">
          共 {{ total }} 条记录 第{{ currentPage }}/{{ Math.ceil(total/pageSize) }}页
        </span>
      </template>
    </el-pagination>
  </div>
</template>

<script>
export default {
  methods: {
    deleteBook(row) {
      const _this = this
      axios.delete('http://localhost:8181/book/deleteById/' + row.id).then(function (resp) {
        _this.$alert('《' + row.name + '》删除成功！', '消息', {
          confirmButtonText: '确定',
          callback: action => {
            _this.fetchData(_this.currentPage)
          }
        })
      })
    },
    edit(row) {
      this.$router.push({
        path: '/admin/update',
        query: {
          id: row.id
        }
      })
    },
    page(currentPage) {
      this.currentPage = currentPage
      this.fetchData(currentPage)
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.fetchData(1)
    },
    fetchData(page) {
      const _this = this
      // 计算总页数
      const totalPages = Math.ceil(_this.total / _this.pageSize)

      // 如果请求页码超出范围，重置为第一页
      if (page > totalPages && totalPages > 0) {
        page = 1
        _this.currentPage = 1
      }

      const pageIndex = page - 1 // 转换为0-based索引
      console.log('请求分页数据 - 前端页码:', page, '后端页码参数:', pageIndex, '每页大小: 5', '完整URL:', `http://localhost:8181/book/findAll/${pageIndex}/5`)

      // 显示加载状态
      _this.tableData = []
      _this.loading = true

      axios
        .get('http://localhost:8181/book/findAll/' + pageIndex + '/5')
        .then(function (resp) {
          if (!resp.data || !resp.data.data) {
            throw new Error('Invalid response format')
          }

          console.log('分页响应数据:', {
            请求页码: page,
            返回数据量: resp.data.data.length,
            数据ID列表: resp.data.data.map(book => book.id),
            每页大小: 5,
            总记录数: resp.data.total
          })

          // 更新数据
          _this.tableData = resp.data.data
          _this.total = resp.data.total
          _this.currentPage = page
        })
        .catch(error => {
          console.error('获取数据失败:', error)
          _this.$message.error('加载数据失败')
        })
        .finally(() => {
          _this.loading = false
        })
    }
  },

  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: []
    }
  },

  created() {
    this.fetchData(1)
  }
}
</script>